{% extends "learning/base.html" %}
{% load static %}

{% block title %}{{ training.title }} - 专题训练{% endblock %}

{% block extra_head %}
<script>
    window.MathJax = {
        tex: {
            inlineMath: [
                ["$", "$"],
                ["\\(", "\\)"]
            ],
            displayMath: [
                ["$$", "$$"],
                ["\\[", "\\]"]
            ]
        },
        startup: {
            pageReady: () => {
                return MathJax.startup.defaultPageReady().then(() => {
                    console.log('MathJax initial typesetting complete');
                });
            }
        }
    };
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" id="MathJax-script" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js" crossorigin="anonymous"></script>
<style>
    .spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(99, 102, 241, 0.2);
        border-top-color: var(--accent);
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    
    .question-card {
        background: var(--surface-elevated);
        border: 2px solid var(--border-subtle);
        border-radius: var(--radius-lg);
        padding: 2rem;
        margin-bottom: 1.5rem;
    }
    
    .answer-section {
        background: var(--accent-soft);
        border: 1px solid var(--accent-light);
        border-radius: var(--radius-md);
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .ai-response {
        background: var(--surface);
        border: 1px solid var(--border-subtle);
        border-radius: var(--radius-md);
        padding: 1.5rem;
        margin-top: 1.5rem;
        line-height: 1.8;
    }
    
    .choice-buttons {
        display: flex;
        gap: 1rem;
        margin-top: 1.5rem;
    }
    
    .choice-button {
        flex: 1;
        padding: 1rem;
        border-radius: var(--radius-md);
        border: 2px solid var(--border-medium);
        background: var(--surface-elevated);
        cursor: pointer;
        transition: all var(--transition-fast);
        font-weight: 600;
        font-size: 1rem;
    }
    
    .choice-button:hover {
        border-color: var(--accent);
        background: var(--accent-soft);
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
    }
    
    .choice-button.correct {
        border-color: var(--success);
        background: var(--success-light);
    }
    
    .choice-button.wrong {
        border-color: var(--danger);
        background: var(--danger-light);
    }
</style>
{% endblock %}

{% block content %}
<div class="card">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.5rem;flex-wrap:wrap;gap:1rem;">
        <div>
            <div style="display:flex;align-items:center;gap:0.75rem;margin-bottom:0.5rem;">
                <a href="{% url 'learning:topic_training_list' %}" class="button small secondary">
                    ← 返回列表
                </a>
                <h2 style="margin:0;">{{ training.title }}</h2>
            </div>
            <p style="margin:0;color:var(--text-secondary);font-size:0.9375rem;">
                已答 {{ answer_count }} 题
            </p>
        </div>
        <div style="display:flex;align-items:center;gap:0.75rem;">
            {% if is_completed %}
                <span class="pill success">✓ 训练完成</span>
            {% else %}
                <span class="pill">第 {{ current_question.question_number }} 题</span>
            {% endif %}
        </div>
    </div>
</div>

{% if is_completed %}
<div class="card">
    <div style="text-align:center;padding:3rem 2rem;">
        <div style="font-size:4rem;margin-bottom:1.5rem;">🎉</div>
        <h3 style="margin:0 0 1rem 0;">恭喜你完成了本次训练！</h3>
        <p style="margin:0 0 2rem 0;color:var(--text-secondary);font-size:1rem;">
            共完成 {{ answer_count }} 道题目
        </p>
        <div class="action-group" style="justify-content:center;">
            <a href="{% url 'learning:topic_training_start' training.pk %}" class="button">
                🔄 重新开始
            </a>
            <a href="{% url 'learning:topic_training_list' %}" class="button secondary">
                返回列表
            </a>
        </div>
    </div>
</div>
{% else %}

<div class="question-card">
    <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:1rem;">
        <span class="hero-badge">第 {{ current_question.question_number }} 题</span>
    </div>
    
    <div style="font-size:1.125rem;line-height:1.8;margin-bottom:1.5rem;white-space:pre-wrap;" id="question-text">{{ current_question.question_text }}</div>
    
    {% if current_question.question_image %}
    <div style="margin-top:1.5rem;text-align:center;">
        <img src="{{ current_question.question_image.url }}" 
             alt="题目图片" 
             style="max-width:100%;height:auto;border-radius:var(--radius-md);box-shadow:var(--shadow-md);">
    </div>
    {% endif %}
</div>

<div class="answer-section" id="answer-section">
    <h3 style="margin:0 0 1rem 0;">✍️ 你的答案</h3>
    <form id="answer-form" enctype="multipart/form-data" data-submit-url="{% url 'learning:topic_training_submit_answer' training.pk %}" data-next-url="{% url 'learning:topic_training_next_question' training.pk %}">
        {% csrf_token %}
        <textarea 
            name="answer" 
            id="answer-input" 
            rows="6" 
            placeholder="请输入你的答案或解题过程...&#10;&#10;提示：可以详细描述你的解题思路" 
            required
            style="width:100%;margin-bottom:1rem;"
        ></textarea>
        
        <div style="margin-bottom:1rem;">
            <label for="answer-image-input" class="button secondary small" style="cursor:pointer;display:inline-flex;align-items:center;gap:0.5rem;">
                <span>📷</span>
                <span id="upload-label">上传答案图片（可选）</span>
            </label>
            <input 
                type="file" 
                name="answer_image" 
                id="answer-image-input" 
                accept="image/*"
                style="display:none;"
            />
            <div id="image-preview" style="margin-top:0.5rem;display:none;">
                <div style="position:relative;display:inline-block;">
                    <img id="preview-img" src="" alt="预览" style="max-width:200px;max-height:200px;border-radius:var(--radius-md);border:2px solid var(--border-subtle);">
                    <button 
                        type="button" 
                        id="remove-image" 
                        class="button small danger"
                        style="position:absolute;top:-8px;right:-8px;width:28px;height:28px;padding:0;border-radius:50%;display:flex;align-items:center;justify-content:center;"
                    >✕</button>
                </div>
            </div>
        </div>
        
        <button type="submit" class="button" id="submit-btn">
            <span id="submit-text">📤 提交并获取AI解析</span>
            <span id="submit-loading" style="display:none;">
                <span class="spinner" style="width:14px;height:14px;border-width:2px;"></span>
                正在分析...
            </span>
        </button>
    </form>
    
    <div id="feedback" class="message" style="display:none;margin-top:1rem;"></div>
</div>

<div id="ai-response-section" style="display:none;">
    <div class="card">
        <h3 style="margin:0 0 1rem 0;">🤖 AI 助教解析</h3>
        <div class="ai-response" id="ai-response-content"></div>
        
        <div style="margin-top:1.5rem;padding-top:1.5rem;border-top:1px solid var(--border-subtle);">
            <h4 style="margin:0 0 1rem 0;">请自行判断答题结果</h4>
            <p style="margin:0 0 1rem 0;color:var(--text-secondary);font-size:0.875rem;">
                根据AI的解析，你认为自己答对了还是答错了？
            </p>
            
            <div class="choice-buttons">
                <button class="choice-button correct" id="correct-btn" type="button">
                    <div style="font-size:2rem;margin-bottom:0.5rem;">✓</div>
                    <div>我答对了</div>
                </button>
                <button class="choice-button wrong" id="wrong-btn" type="button">
                    <div style="font-size:2rem;margin-bottom:0.5rem;">✗</div>
                    <div>我答错了</div>
                </button>
            </div>
        </div>
    </div>
</div>

{% endif %}
<script>
// Inlined from static file: learning/topic_training_question.js
(function() {
    // Get elements
    const answerForm = document.getElementById('answer-form');
    if (!answerForm) return; // Completed state, no form on page

    const answerInput = document.getElementById('answer-input');
    const submitBtn = document.getElementById('submit-btn');
    const submitText = document.getElementById('submit-text');
    const submitLoading = document.getElementById('submit-loading');
    const feedback = document.getElementById('feedback');
    const aiResponseSection = document.getElementById('ai-response-section');
    const aiResponseContent = document.getElementById('ai-response-content');
    const correctBtn = document.getElementById('correct-btn');
    const wrongBtn = document.getElementById('wrong-btn');
    const questionText = document.getElementById('question-text');
    const answerImageInput = document.getElementById('answer-image-input');
    const imagePreview = document.getElementById('image-preview');
    const previewImg = document.getElementById('preview-img');
    const removeImageBtn = document.getElementById('remove-image');
    const uploadLabel = document.getElementById('upload-label');

    // URLs via data attributes
    const submitUrl = answerForm.dataset.submitUrl;
    const nextUrl = answerForm.dataset.nextUrl;

    // CSRF helper
    function getCsrfToken() {
        const input = answerForm.querySelector('input[name="csrfmiddlewaretoken"]');
        return input ? input.value : '';
    }

    let currentAnswer = '';
    let currentAnswerImageUrl = '';
    let hasUploadedImage = false;
    let isSubmitting = false;

    // Marked config if present
    if (window.marked && typeof window.marked.setOptions === 'function') {
        window.marked.setOptions({ breaks: true, gfm: true });
    }

    function renderMarkdown(text) {
        let html;
        if (window.marked && typeof window.marked.parse === 'function') {
            html = window.marked.parse(text);
        } else {
            html = (text || '').replace(/\n/g, '<br>');
        }
        if (window.DOMPurify && typeof window.DOMPurify.sanitize === 'function') {
            html = window.DOMPurify.sanitize(html);
        }
        return html;
    }

    function typesetMath(element, attempt = 0) {
        if (!element) return;
        if (window.MathJax && window.MathJax.typesetPromise) {
            window.MathJax.typesetPromise([element]).catch(err => {
                console.error('MathJax typeset failed:', err);
            });
        } else if (attempt < 10) {
            setTimeout(() => typesetMath(element, attempt + 1), 200);
        }
    }

    // Initial typeset for question text
    if (questionText) {
        typesetMath(questionText);
    }

    // Image upload handlers
    if (answerImageInput) {
        answerImageInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                if (!file.type.startsWith('image/')) {
                    showFeedback('请上传图片文件', 'error');
                    answerImageInput.value = '';
                    return;
                }
                if (file.size > 5 * 1024 * 1024) {
                    showFeedback('图片大小不能超过5MB', 'error');
                    answerImageInput.value = '';
                    return;
                }
                const reader = new FileReader();
                reader.onload = function(ev) {
                    if (previewImg) previewImg.src = ev.target.result;
                    if (imagePreview) imagePreview.style.display = 'block';
                    if (uploadLabel) uploadLabel.textContent = '更换图片';
                };
                reader.readAsDataURL(file);
            }
        });
    }

    if (removeImageBtn) {
        removeImageBtn.addEventListener('click', function() {
            if (answerImageInput) answerImageInput.value = '';
            if (imagePreview) imagePreview.style.display = 'none';
            if (previewImg) previewImg.src = '';
            if (uploadLabel) uploadLabel.textContent = '上传答案图片（可选）';
        });
    }

    function showFeedback(message, type = 'info') {
        if (!feedback) return;
        feedback.style.display = 'block';
        feedback.className = `message message-${type}`;
        feedback.textContent = message;
    }

    function hideFeedback() {
        if (!feedback) return;
        setTimeout(() => {
            feedback.style.display = 'none';
        }, 3000);
    }

    function setSubmitting(submitting) {
        isSubmitting = submitting;
        if (submitBtn) submitBtn.disabled = submitting;
        if (answerInput) answerInput.disabled = submitting;
        if (submitText) submitText.style.display = submitting ? 'none' : 'inline';
        if (submitLoading) submitLoading.style.display = submitting ? 'inline-flex' : 'none';
    }

    // Submit answer via AJAX
    answerForm.addEventListener('submit', async (e) => {
        try {
            e.preventDefault();
            e.stopPropagation();
        } catch (_) {}

        if (isSubmitting) return;

        currentAnswer = (answerInput && answerInput.value ? answerInput.value : '').trim();

        if (!currentAnswer) {
            showFeedback('请输入您的答案', 'error');
            if (answerInput) answerInput.focus();
            return;
        }

        // 先构建 FormData，避免因禁用输入导致字段被省略
        let formData = new FormData(answerForm);
        if (!formData.has('answer')) {
            formData.append('answer', currentAnswer);
        }
    
        setSubmitting(true);
        showFeedback('🔄 正在请求AI解析...', 'info');

        try {
            // Ensure CSRF present (FormData(answerForm) should include it, but keep safe)
            if (!formData.has('csrfmiddlewaretoken')) {
                formData.append('csrfmiddlewaretoken', getCsrfToken());
            }

            const response = await fetch(submitUrl, {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: formData,
            });

            const data = await response.json().catch(() => ({}));

            if (!response.ok) {
                showFeedback('❌ ' + (data.error || '提交失败'), 'error');
                setSubmitting(false);
                return;
            }

            if (data.answer) {
                if (aiResponseContent) {
                    aiResponseContent.innerHTML = renderMarkdown(data.answer);
                    typesetMath(aiResponseContent);
                }
                if (aiResponseSection) aiResponseSection.style.display = 'block';

                if (answerImageInput && answerImageInput.files && answerImageInput.files.length > 0) {
                    currentAnswerImageUrl = answerImageInput.files[0].name;
                    hasUploadedImage = true;
                } else {
                    currentAnswerImageUrl = '';
                    hasUploadedImage = false;
                }

                setTimeout(() => {
                    if (aiResponseSection) aiResponseSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }, 100);

                showFeedback('✅ AI解析已生成', 'success');
                hideFeedback();
            } else {
                showFeedback('⚠️ 未收到AI解析', 'warning');
            }
        } catch (error) {
            console.error('提交错误:', error);
            showFeedback('❌ 网络错误：' + (error && error.message ? error.message : '未知错误'), 'error');
        } finally {
            setSubmitting(false);
        }
    });

    // Next question choice
    function bindChoiceHandlers() {
        async function handleChoice(isCorrect) {
            if (!correctBtn || !wrongBtn) return;
            correctBtn.disabled = true;
            wrongBtn.disabled = true;

            const chosenBtn = isCorrect ? correctBtn : wrongBtn;
            const originalHTML = chosenBtn.innerHTML;
            chosenBtn.innerHTML = '<span class="spinner" style="width:20px;height:20px;"></span>';

            try {
                const formData = new FormData();
                formData.append('is_correct', isCorrect);
                formData.append('answer', currentAnswer);
                if (hasUploadedImage) formData.append('has_image', 'true');
                if (currentAnswerImageUrl) formData.append('answer_image_url', currentAnswerImageUrl);
                formData.append('csrfmiddlewaretoken', getCsrfToken());

                const response = await fetch(nextUrl, {
                    method: 'POST',
                    headers: { 'X-Requested-With': 'XMLHttpRequest' },
                    body: formData,
                });

                const data = await response.json().catch(() => ({}));

                if (!response.ok) {
                    showFeedback('❌ ' + (data.error || '操作失败'), 'error');
                    chosenBtn.innerHTML = originalHTML;
                    correctBtn.disabled = false;
                    wrongBtn.disabled = false;
                    return;
                }

                if (data.has_next) {
                    showFeedback('✅ ' + (data.message || '正在跳转到下一题'), 'success');
                    setTimeout(() => { window.location.reload(); }, 800);
                } else {
                    showFeedback('🎉 ' + (data.message || '本次训练已完成'), 'success');
                    setTimeout(() => { window.location.reload(); }, 1200);
                }
            } catch (error) {
                console.error('切题错误:', error);
                showFeedback('❌ 网络错误：' + (error && error.message ? error.message : '未知错误'), 'error');
                chosenBtn.innerHTML = originalHTML;
                correctBtn.disabled = false;
                wrongBtn.disabled = false;
            }
        }

        if (correctBtn) correctBtn.addEventListener('click', () => handleChoice(true));
        if (wrongBtn) wrongBtn.addEventListener('click', () => handleChoice(false));
    }

    bindChoiceHandlers();
})();
</script>
{% endblock %}
